import os
import re
import subprocess
from Cheetah.Template import Template
import LiseWeb
import Error



class LisePDF(LiseWeb.LiseWeb):
    """
    Implements the operations related to generate a PDF document from a LiSe definition

    """

    def __init__(self, lisePath):
        """Arguments:
        lisePath(string) -- LiSe XML file path

        """
        LiseWeb.LiseWeb.__init__(self, lisePath)

    def _determine_path(self):
        """Borrowed from wxglade.py"""
        try:
            root = __file__
            if os.path.islink(root):
                root = os.path.realpath(root)
            return os.path.dirname(os.path.abspath(root))
        except:
            print "I'm sorry, but something is wrong."
            print "There is no __file__ variable. Please contact the author."
            sys.exit()



    def _stripHTML(self, string):
        """

        """
        p = re.compile(r'<.*?>')
        string = p.sub('', string)
        return string

    def _execPdflatex(self, outputPath, texOutputPath, removeTexFile):
        """

        """
        actualPath = os.getcwd()
        os.chdir(os.path.dirname(texOutputPath))
        cmd = ['pdflatex', os.path.basename(texOutputPath)]
        pipe = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE)
        pipe.communicate()
        os.chdir(actualPath)
        if os.path.exists(texOutputPath[:-4] + '.pdf'):
            # shutil.move() os.rename()
            os.rename(texOutputPath[:-4] + '.pdf', outputPath)
            os.remove(texOutputPath[:-4] + '.aux')
            os.remove(texOutputPath[:-4] + '.log')
            os.remove(texOutputPath[:-4] + '.out')
            if removeTexFile:
                os.remove(texOutputPath)
            else:
                os.rename(texOutputPath, os.path.join(os.path.dirname(outputPath), os.path.basename(texOutputPath)))

    def GeneratePDF(self, outputPath, digiDirPath, langId='es', removeTexFile=True):
        """

        """
        if not os.path.exists(digiDirPath):
            raise Error.Error(301, 'Picture directory path not found: "' + digiDirPath + '"')
        if not os.path.exists(os.path.dirname(outputPath)):
            raise Error.Error(302, 'PDF directory path not found: "' + os.path.dirname(outputPath) + '"')
        texOutputPath = os.path.join(digiDirPath, os.path.basename(outputPath)[:-4]+'.tex')

        # Retrieves all the metadata in an apropiate format for the Cheetah template
        pictures = [i for i in os.listdir(digiDirPath) if i.endswith('.jpg')]
        indexNameSpace = self.metadata[langId].getIndexLeaves()
        numberOfPictures = self.metadata[langId].getNumberOfPictures()

        # Assign each entry of the index to the appropiate digitised picture
        index = []
        nIndexNameSpace = 0
        nPictures = 0
        while nIndexNameSpace < len(indexNameSpace) and nPictures < len(pictures):
            nPicturesPerPage = 0
            while (nPicturesPerPage < indexNameSpace[nIndexNameSpace]['picturesPerPage'] and
                   nPictures < len(pictures)):
                indexEntry = {'pageTitle': indexNameSpace[nIndexNameSpace]['pageTitle']}
                indexEntry['pageTitle'] = self._stripHTML(indexEntry['pageTitle'])
                indexEntry['pictureFilename'] = pictures[nPictures]
                index.append(indexEntry)
                nPictures += 1
                nPicturesPerPage += 1
            nIndexNameSpace += 1

        nameSpace = {'index':index}

        # Fills the metadata in the template and generates the lise TeX file
        try:
            t = Template(file=os.path.join(self._determine_path(), 'templates', 'tex.tmpl'), 
                         searchList=[nameSpace])
        except:
            raise Error.Error(350, 'Error filling in the TeX LiSe template')
        try:
            texFile = open(texOutputPath, 'w')
            texFile.write(str(t))
            texFile.close()
        except:
            raise Error.Error(351, 'Error creating/writing the TeX LiSe')

        self._execPdflatex(outputPath, texOutputPath, removeTexFile)



